package com.ladlee.parking.config.handler;


import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ladlee.parking.util.R;
import com.ladlee.parking.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {

        logger.info("登录失败");

//        String message = "";
//        response.setContentType("application/json;charset=UTF-8");
//        if (exception instanceof BadCredentialsException) {
//            message = "用户名或密码错误";
//            response.getWriter().write(objectMapper.writeValueAsString(R.failed(message)));
//        } else {
//            response.getWriter().write(objectMapper.writeValueAsString(R.failed(exception.getMessage())));
//        }
        log.debug("表单登录失败:{}", exception.getLocalizedMessage());
        WebUtils.getResponse().sendRedirect(String.format("/token/login?error=%s"
                , HttpUtil.encodeParams(exception.getMessage(), Charset.forName("UTF-8"))));
    }
}
